# Replaces URL the 'image' parameter in a PBB template on Wikipedia
# to point to the version produced by PDBbot.
#
# Author: emw

import urllib.request, re, time, subprocess

entrez_RE = re.compile("id_type\=entrezgene\&amp\;id\=(\d+)\"")

# Wikipedia makes it difficult for screen scrapers; 
# setting a mask 'user-agent' bypasses this obstacle
class AppURLopener(urllib.request.FancyURLopener):
	version = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)"

# Given a HUGO ID for a protein of interest, scrapes its Entrez ID 
# from the protein's Wikipedia article
def scrape_entrez_id(protein_id):
	#print("in")
	urllib._urlopener = AppURLopener()
	fp = urllib._urlopener.open("http://en.wikipedia.org/wiki/" + protein_id)
	mybytes = str(fp.read())
	fp.close()
	return entrez_RE.findall(mybytes)[0]

# Using the comma-separated values (of form HUGO ID, PDB ID)
# in data/protein_and_pdb_list.txt, replaces image URL 
# in a PBB template
def replace_protein_image():
	i = 0
	with open("data/protein_and_pdb_list.txt", "r") as input_file:
			for line in input_file:
				if i < 5:
					split_line = line.partition(",")
					if (split_line[2][1] != " "):
						hugo_id = split_line[0]
						pdb_id = split_line[2][1:5]
						entrez_id = scrape_entrez_id(hugo_id)
						print(hugo_id + ", " + pdb_id + ", " + entrez_id)
					else:
						print("PDB ID not found")
					
					subprocess.Popen("py25 pywikipedia\\replace.py -always -log -page:Template:PBB/" + entrez_id + " \"PBB_Protein_" + hugo_id + "_image.jpg\" \"Protein_" + hugo_id + "_PDB_" + pdb_id + ".png\" -summary:\"Changed protein structure image to new version\"")
					print ("Upload complete, sleeping for 15 seconds, i = " + str(i))
					time.sleep(15)
					i += 1

replace_protein_image()